import { Location } from '@nutui/icons-react-taro'
import { Address, Cell } from '@nutui/nutui-react-taro'
import { Text, View } from '@tarojs/components'
import { useEffect, useMemo, useState } from 'react'
import './index.less'

interface AddressList {
  id?: string | number
  provinceName: string
  cityName: string
  countyName: string
  townName: string
  addressDetail: string
  selectedAddress?: boolean
  name?: string
  phone?: string
}

interface AddressSelectProps {
  onChange?: (data: AddressList) => void
  value?: AddressList
  options: AddressList[]
}

const AddressSelect = ({ onChange, value, options }: AddressSelectProps) => {
  const [text, setText] = useState('请选择地址')
  const [name, setName] = useState('')
  const [phone, setPhone] = useState('')
  const [visible, setVisible] = useState(false)

  const existList = useMemo(() => {
    return options.map((item) => ({
      ...item,
      selectedAddress: item.id === value?.id,
    }))
  }, [options, value?.id])

  useEffect(() => {
    if (value) {
      setText(value.provinceName + value.cityName + value.countyName + value.townName + value.addressDetail)
      setName(value?.name || '')
      setPhone(value?.phone || '')
    }
  }, [value])

  const selectedTwo = (data: AddressList) => {
    onChange && onChange(data)
  }

  return (
    <>
      <Cell
        title={
          <View className='cell-content'>
            <Location />
            <View className='cell-content-text'>
              <Text>{name}</Text>
              <Text>{phone}</Text>
              <Text>{text}</Text>
            </View>
          </View>
        }
        onClick={() => setVisible(true)}
      />
      <Address
        visible={visible}
        type='exist'
        existList={existList}
        onExistSelect={selectedTwo}
        title='配送'
        onClose={() => setVisible(false)}
      />
    </>
  )
}
export default AddressSelect
